﻿namespace ChinaUnicom.Tasks
{
    using ChinaUnicom.Schedule;
    using System;
    using System.Windows;

    internal class AutoLoginTask : ITask
    {
        static AutoLoginTask() { task = new AutoLoginTask(); }

        private AutoLoginTask() { Message = string.Empty; }

        public string Message { get; private set; }

        Context Context { get { return (Application.Current as App).Context; } }

        static AutoLoginTask task;
        public static AutoLoginTask Task { get { return task; } }

        public void Start()
        {
            if (Started != null) {
                Started(this, EventArgs.Empty);
            }

            Factory.Operation.AutoLogin(status =>
            {
                if (status.StatusCode == System.Net.HttpStatusCode.OK && status.Result.Contains(Context.Account.Mobile))
                {
                    Authentication.Current.Signed = true;

                    if (Completed != null)
                    {
                        Completed(this, EventArgs.Empty);
                    }
                }
                else
                {
                    Message = Factory.Parser.Failed(status.Result);
                    RaiseFailed();
                }
            });
        }

        public int Pending { get { return 0; } }

        public event EventHandler Completed;

        public event EventHandler Failed;

        void RaiseFailed()
        {
            if (Failed != null)
            {
                Failed(this, EventArgs.Empty);
            }
        }


        public event EventHandler Started;
    }
}
